/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ProducaoView.java
 *
 * Created on 02/11/2011, 16:59:16
 */
package praticav.view;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import org.hibernate.HibernateException;
import org.hibernate.exception.ConstraintViolationException;
import praticav.dao.ProducaoDAO;
import praticav.dao.TipoUvaDAO;
import praticav.model.Producao;
import praticav.model.TipoUva;

/**
 *
 * @author Katiane
 */
public class ProducaoView extends javax.swing.JFrame {
    int cod;
    int anoPro;
    int tipo;
    int quant;
    int conta; 
    int Sequencial;
    Producao prod;
    /** Creates new form ProducaoView */
    public ProducaoView() {
        initComponents();
        conta = 0;
        
        Date d = new Date();
        Calendar calendario = new GregorianCalendar();
        calendario.setTime(d);
        txtAno.setText(""+calendario.get(Calendar.YEAR));
       
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtQuantidade = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        cbxTipoUva = new javax.swing.JComboBox();
        jPanel3 = new javax.swing.JPanel();
        txtAno = new javax.swing.JTextField();
        btnSalvar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        txtDtaFim = new javax.swing.JTextField();

        setTitle("Cadastro da Produção");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Quantidade"));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(42, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(txtQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Tipo de Uva"));

        cbxTipoUva.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione" }));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cbxTipoUva, 0, 354, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(cbxTipoUva, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Ano da Produção"));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(263, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/praticav/images/save.png"))); // NOI18N
        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/praticav/images/close.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Data Final"));

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtDtaFim, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(txtDtaFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 197, Short.MAX_VALUE)
                        .addComponent(btnCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnSalvar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    /*
    public ProducaoView(int codigo, int ano, int tipouva, int quantidade) {
            cod = codigo;
            anoPro = ano;
            tipo = tipouva;
            quant = quantidade;
            conta=1;

        initComponents();
  
    }
     * 
     */

    public ProducaoView(Producao p) {
            cod = p.getProcodigo();
            anoPro = p.getProano();
            tipo = p.getTipoUva().getUvacodigo();
            quant = p.getProquantidade();
            Sequencial = p.getProsequencia();
            prod = p;
            conta=1;

        initComponents();
  
    }    
    
    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        if (txtAno.getText().equals("") || txtQuantidade.getText().equals(""))
      {
          JOptionPane.showMessageDialog(null, "O campo DESCRIÇÃO e QUANTIDADE devem estar preenchidos!", "Atenção", WIDTH);
      } else
      {
          if (conta==0)
          {
            int err=0;
            Producao f = new Producao();
            f.setProano(Integer.parseInt(txtAno.getText()));
            f.setTipouva((TipoUva) cbxTipoUva.getSelectedItem());
            f.setProquantidade(Integer.parseInt(txtQuantidade.getText()));
            f.setProsequencia(1);

            SimpleDateFormat formatarDate = new SimpleDateFormat("dd/MM/yyyy");   

            //String DataStrFim = formatarDate.format(txtDtaFim);

            try {
                f.setProdtainicio(new SimpleDateFormat("dd/MM/yyyy").parse("01/01/2011"));
            } catch (ParseException e) {
                JOptionPane.showMessageDialog(null, "Data incorreta!");
            }

            try {
                f.setProdtafim(new SimpleDateFormat("dd/MM/yyyy").parse(txtDtaFim.getText()));
            } catch (ParseException e) {
                JOptionPane.showMessageDialog(null, "Data incorreta!");
                err=1;
            }
            
            if (err==0){
                ProducaoDAO dao = new ProducaoDAO();
                try{
                    dao.inserir(f);
                } catch(ConstraintViolationException ce){
                    JOptionPane.showMessageDialog(null, "Erro ao gravar os dados!!!  "+ ce.getMessage());
                } catch (HibernateException ex){
                    JOptionPane.showMessageDialog(null, "Erro: "+ex.getMessage());
                }
                txtAno.setText("");
                txtQuantidade.setText("");
                this.hide();
            }
            txtDtaFim.setText("");

          } 
          else
          {
            Producao f = new Producao();
            f.setProcodigo(cod);
            f.setProano(Integer.parseInt(txtAno.getText()));
            f.setTipouva((TipoUva) cbxTipoUva.getSelectedItem());
            f.setProquantidade(Integer.parseInt(txtQuantidade.getText()));
            f.setProsequencia(Sequencial);

            SimpleDateFormat formatarDate = new SimpleDateFormat("dd/MM/yyyy");   
            String DataStrIni = formatarDate.format(prod.getProdtainicio());

            //JOptionPane.showMessageDialog(null, "Data: "+txtDtaFim.getText());
            //String DataStrFim = formatarDate.format(txtDtaFim.getText());

            try {
                f.setProdtainicio(new SimpleDateFormat("dd/MM/yyyy").parse(DataStrIni));
            } catch (ParseException e) {
                JOptionPane.showMessageDialog(null, "Data incorreta!");
            }

            try {
                f.setProdtafim(new SimpleDateFormat("dd/MM/yyyy").parse(txtDtaFim.getText()));
            } catch (ParseException e) {
                JOptionPane.showMessageDialog(null, "Data incorreta!");
            }
            
            ProducaoDAO dao = new ProducaoDAO();
            
            try{
                dao.editar(f);
            } catch(ConstraintViolationException ce){
                JOptionPane.showMessageDialog(null, "Erro ao modificar os dados!!!  "+ ce.getMessage());
            } catch (HibernateException ex){
                JOptionPane.showMessageDialog(null, "Erro: "+ex.getMessage());
            }

            txtAno.setText("");
            txtQuantidade.setText("");
            this.hide();
          }
      }  
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.hide();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        DefaultComboBoxModel cmodel =  
          new DefaultComboBoxModel(  
             new Vector( new TipoUvaDAO().listar() ) 
          ); 
        cbxTipoUva.setModel(cmodel); 
      
        txtAno.setText(""+anoPro);
        txtQuantidade.setText(""+quant);
        TipoUva t = new TipoUvaDAO().buscar(tipo); 
        cbxTipoUva.getModel().setSelectedItem(t);
        SimpleDateFormat formatarDate = new SimpleDateFormat("dd/MM/yyyy");   
        String DataStrFim = formatarDate.format(prod.getProdtafim());
        txtDtaFim.setText(DataStrFim);

        
        if (conta == 0)
        {
            this.setTitle("Cadastro da Produção");
        }else
        {
            this.setTitle("Alteração da Produção");
        }
    }//GEN-LAST:event_formWindowOpened

    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JComboBox cbxTipoUva;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JTextField txtAno;
    private javax.swing.JTextField txtDtaFim;
    private javax.swing.JTextField txtQuantidade;
    // End of variables declaration//GEN-END:variables
}
